<route lang="json5">
{
  layout: 'noTabBar',
  style: {
    navigationBarTitleText: '注册',
    navigationStyle: 'custom',
  },
}
</route>

<template>
  <view class="register-container p-4">
    <view class="back-btn" @click="goToLogin">
      <text class="iconfont icon-arrow-left text-lg"></text>
    </view>

    <view class="logo-box text-center mt-8 mb-12">
      <image src="/static/logo.jpg" class="w-22 h-10 inline-block" />
      <view class="text-2xl font-bold mt-4">4G门禁管理系统</view>
    </view>

    <wd-form :model="formData" :rules="rules" ref="registerForm">
      <wd-form-item prop="phone" label="手机号">
        <wd-input
          v-model="formData.phone"
          placeholder="请输入手机号"
          clearable
          type="number"
          :maxlength="11"
        />
      </wd-form-item>

      <wd-form-item prop="smsCode" label="验证码">
        <view class="flex">
          <wd-input
            v-model="formData.smsCode"
            placeholder="请输入验证码"
            clearable
            type="number"
            :maxlength="6"
            class="flex-1"
          />
          <wd-button
            size="small"
            :disabled="!!countdown"
            @click="handleSendCode"
            :loading="sendingCode"
            class="ml-2 verify-code-btn"
          >
            {{ countdown ? `${countdown}s` : '获取验证码' }}
          </wd-button>
        </view>
      </wd-form-item>

      <wd-form-item prop="password" label="密码">
        <wd-input
          v-model="formData.password"
          placeholder="请设置密码"
          clearable
          :show-password="true"
        />
      </wd-form-item>

      <wd-form-item prop="confirmPassword" label="确认密码">
        <wd-input
          v-model="formData.confirmPassword"
          placeholder="请确认密码"
          clearable
          :show-password="true"
        />
      </wd-form-item>
    </wd-form>

    <view class="mt-8">
      <wd-button type="primary" block @click="handleRegister" :loading="loading">注册</wd-button>
    </view>

    <!-- <view class="text-center mt-4">
      <text class="text-gray-500 text-sm" @click="goToLogin">已有账号，去登录</text>
    </view> -->
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { registerAPI, registerCommunityAPI, sendSmsCodeAPI } from '@/service/iam'
import { onLoad } from '@dcloudio/uni-app'
import { FormRules } from 'wot-design-uni/components/wd-form/types'

const loading = ref(false)
const sendingCode = ref(false)
const countdown = ref(0)

const formData = ref({
  phone: '',
  smsCode: '',
  password: '',
  confirmPassword: '',
})

const rules: FormRules = {
  phone: [
    { required: true, message: '请输入手机号' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', required: true },
  ],
  smsCode: [
    { required: true, message: '请输入验证码' },
    { pattern: /^\d{6}$/, message: '验证码为6位数字', required: true },
  ],
  password: [
    { required: true, message: '请设置密码' },
    { min: 6, max: 20, message: '密码长度为6-20位', required: true },
  ],
  confirmPassword: [
    { required: true, message: '请确认密码' },
    {
      validator: (val: string) => val === formData.value.password,
      message: '两次输入的密码不一致',
      required: true,
    },
  ],
}

const registerForm = ref<any>()

const communityId = ref('')

onLoad((options) => {
  if (options.communityId) {
    communityId.value = options.communityId
  }
})

const startCountdown = () => {
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

const handleSendCode = async () => {
  try {
    await registerForm.value?.validateField('phone')
    sendingCode.value = true

    const res = await sendSmsCodeAPI({
      phone: formData.value.phone,
    })

    if (res.code === 200) {
      uni.showToast({
        title: '验证码已发送',
        icon: 'success',
      })
      startCountdown()
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    uni.showToast({
      title: '发送验证码失败',
      icon: 'error',
    })
  } finally {
    sendingCode.value = false
  }
}

const handleRegister = async () => {
  try {
    await registerForm.value?.validate()
    loading.value = true

    if (communityId.value) {
      const res = await registerCommunityAPI({
        phone: formData.value.phone,
        password: formData.value.password,
        smsCode: formData.value.smsCode,
        communityId: communityId.value,
      })

      if (res.code === 200) {
        uni.showToast({
          title: '注册成功',
          icon: 'success',
        })

        setTimeout(() => {
          goToLogin()
        }, 1500)
      }
    } else {
      const res = await registerAPI({
        phone: formData.value.phone,
        password: formData.value.password,
        smsCode: formData.value.smsCode,
      })

      if (res.code === 200) {
        uni.showToast({
          title: '注册成功',
          icon: 'success',
        })

        setTimeout(() => {
          goToLogin()
        }, 1500)
      }
    }
  } catch (error) {
    console.error('注册失败:', error)
    uni.showToast({
      title: '注册失败',
      icon: 'error',
    })
  } finally {
    loading.value = false
  }
}

const goToLogin = () => {
  uni.navigateBack()
}
</script>

<style lang="scss" scoped>
.register-container {
  min-height: 100vh;
  background-color: #f8f8f8;
}

.verify-code-btn {
  width: 200rpx !important;
  height: 34px !important;
  padding: 0 !important;
  font-size: 28rpx !important;
  line-height: 34rpx !important;
  border-radius: 4px !important;

  // 如果按钮是自定义主题色，可以添加以下样式
  // --button-primary-background-color: #018d71;
  // --button-primary-border-color: #018d71;
}

.back-btn {
  position: fixed;
  top: calc(var(--status-bar-height) + 20rpx);
  left: 32rpx;
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 64rpx;
  height: 64rpx;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}
</style>
